#!/usr/bin/python
import processing_unit
import instruction_set
import sys

# processor
def processor(process, program, program_size, debug):
	instruction_set.program = program
	# create debug strings
	if debug == "-d":
		debug_code = ''
		debug_code = 'init' + '   ' + str(program) + '\n'
		debug_register = ''
		debug_register = 'init' + '   ' + str(process.universal_register) + '\n'
	while(True):
		operands = []
		if not 0 <= process.program_counter_register < program_size: print instruction_set.error.output("in_pr_a", process.program_counter_register); return False
		operation = program[process.program_counter_register]
		process.program_counter_register = process.program_counter_register + 1
		if not 0 <= operation < len(instruction_set.instruction_list): print instruction_set.error.output("in_pr_c", process.program_counter_register); return False
		number_operands = instruction_set.instruction_set[instruction_set.instruction_list[operation]]
		if number_operands > 3: print instruction_set.error.output("in_nu_o"); return False
		for i in range(number_operands):
			operands.append(program[process.program_counter_register])
			process.program_counter_register = process.program_counter_register + 1
		op_instruction = instruction_set.instruction_list[operation]
		if instruction_set.instruction.has_key(op_instruction):
			instruction_set.instruction[op_instruction](process, *operands)
			# write content of the memory and register to debug strings
		if debug == "-d":
			debug_code = debug_code + op_instruction + '   ' + str(program) + '\n'
			debug_register = debug_register + op_instruction + '   ' + str(process.universal_register) + '\n'
			# write debug strings to file
			debug_file = open('./' + sys.argv[1] + '_debug', 'w')
			debug_file.write('program code:\n' + debug_code + '\n\nregister:\n' + debug_register)
		if instruction_set.instruction_list[operation] == 'HALT': return False


process = processing_unit.process_status()
#read parameters
try:
	#program file
	program = sys.argv[1]
	try:
		#debug parameter
		debug = sys.argv[2]
	except:
		debug = ""
except:
	print instruction_set.error.output("no_pr")

#read program code in program file
program_file = open(program, 'r')
lines = program_file.readlines()
for i in lines:
	if i[0] != "#":
		code = i.rstrip().lstrip()
program = code.split(", ")
#convert list elements from str to in:
program = [int(i) for i in program]

#call processor with program
program_memory = len(program)
processor(process, program, program_memory, debug)

